package com.mission.schedule.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

	private final static int VERSION = 1;// 版本号

	// 自带的构造方法
	public DBHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	// 为了每次构造时不用传入dbName和版本号，自己得新定义一个构造方法
	public DBHelper(Context cxt) {
		this(cxt, DBSourse.dataBaseName, null, VERSION);// 调用上面的构造方法
	}

	// 版本变更时
	public DBHelper(Context cxt, int version) {
		this(cxt, DBSourse.dataBaseName, null, version);
	}

	// 当数据库创建的时候调用
	public void onCreate(SQLiteDatabase db) {

	}

	// 版本更新时调用
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			db.beginTransaction();
			db.setTransactionSuccessful(); // 设置事务处理成功，不设置会自动回滚不提交
			db.endTransaction(); // 处理完成
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}


	/**
	 * 判断某张表是否存在
	 * @param tabName 表名
	 * @return
	 */
	public boolean tabIsExist(String tabName){
		boolean result = false;
		if(tabName == null){
			return false;
		}
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = this.getReadableDatabase();//此this是继承SQLiteOpenHelper类得到的
			String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"+tabName.trim()+"' ";
			cursor = db.rawQuery(sql, null);
			if(cursor.moveToNext()){
				int count = cursor.getInt(0);
				if(count>0){
					result = true;
				}
			}
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}

	/**
	 * 判断数据库中指定表的指定字段是否存在
	 * @param tableName 指定表名称
	 * @param columnName 执行字段名称
	 * @return
	 */
	public boolean checkColumnExists(String tableName, String columnName) {
		boolean result = false ;
		Cursor cursor = null ;
		SQLiteDatabase db = this.getWritableDatabase();
		try{
			cursor = db.rawQuery( "select * from sqlite_master where name = '" + tableName + "' and sql like '%"+columnName+"%'", null);
			result = null != cursor && cursor.moveToFirst() ;
		}catch (Exception e){
			Log.e("TAG","checkColumnExists..." + e.getMessage()) ;
		}finally{
			if(null != cursor && !cursor.isClosed()){
				cursor.close() ;
			}
		}

		return result ;
	}
}
